package chaw.android.util;

import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.train.ChatRoomActivity;
import chaw.android.train.TrainTravelActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.content.LocalBroadcastManager;

public class C2DMReceiver extends BroadcastReceiver{
	SharedPreferences pref;
	SharedPreferences.Editor prefEditor;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(
				"com.google.android.c2dm.intent.REGISTRATION")) {
			handleRegistration(context, intent);
		} else if (intent.getAction().equals(
				"com.google.android.c2dm.intent.RECEIVE")) {
			handleMessage(context, intent);
		}
	}

	private void handleRegistration(Context context, Intent intent) {
		pref = context.getSharedPreferences("asdf", 0);
		prefEditor = pref.edit();
		
		String registration = intent.getStringExtra("registration_id");
		if (intent.getStringExtra("error") != null) {
//			Log.e("C2DM", "Registeration error" + intent.getStringExtra("error"));
		} else if (intent.getStringExtra("unregistered") != null) {
//			Log.d("C2DM","Unregistered " + intent.getStringExtra("unregistered"));
		} else if (registration != null) {
			// Send the registration ID to the 3rd party site that is sending
			// the messages.
			// This should be done in a separate thread.
			// When done, remember that all registration is done.
//			Log.d("C2DM","Saving Registration_id = " + registration);
//			prefEditor.putString("registration", registration);
//			prefEditor.commit();
			
			LocalBroadcastManager localBroadMgr = LocalBroadcastManager.getInstance(context);
	        Intent intentForRegist = new Intent();
	        intentForRegist.putExtra("isReg", true);
	        intentForRegist.putExtra("registration", registration);
	        intentForRegist.setAction("registration");
	        intentForRegist.addCategory("regist");
	        
	        localBroadMgr.sendBroadcast(intentForRegist);
		}
	}
	
	private void handleMessage(Context context, Intent intent){
		String msg = intent.getStringExtra("answerer").toString();
//		Log.e("C2DM", "handleMessage : " + msg);
		try {
			JSONObject msgData = new JSONObject(msg);
			String type = msgData.getString("type");
			if(type.equalsIgnoreCase("chat")){
				handleChatMessage(msgData, context);
	        }
			else if(type.equalsIgnoreCase("add_reply") || type.equalsIgnoreCase("add_board")){
				handleReplyMessage(msgData, context);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private void handleReplyMessage(JSONObject msgData, Context context){
		try {
			String message = msgData.getString("message");
			String board_id = msgData.getString("board_id");
			String writer_id = msgData.getString("user_id");
			long when = msgData.getLong("when");
			
//			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
			
			if(Preferences.getBoolean(context, "configNewStory")){
		        LocalBroadcastManager localBroadMgr = LocalBroadcastManager.getInstance(context);
		        Intent intentForNewReply = new Intent();
		        intentForNewReply.putExtra("board_id", board_id);
		        intentForNewReply.putExtra("writer_id", writer_id);
		        intentForNewReply.setAction("newFavorite");
		        intentForNewReply.addCategory("newFavorite");
		        
		        localBroadMgr.sendBroadcast(intentForNewReply);

		        Preferences.setBoolean(context, "isNewFavorite", true);
				
	        	Notification notification = new Notification(chaw.android.train.R.drawable.ic_launcher_full, message, when);
		        Intent replyIntent = new Intent(context, TrainTravelActivity.class);
		        replyIntent.putExtra("isReply", true);
		        replyIntent.putExtra("board_id", board_id);
		        replyIntent.putExtra("writer_id", writer_id);
		        
		        PendingIntent pi = PendingIntent.getActivity(context, 0, replyIntent, PendingIntent.FLAG_ONE_SHOT);
		        notification.setLatestEventInfo(context, "Train Travel", message, pi);
		        notification.defaults = Notification.DEFAULT_ALL;
		        notification.flags |= Notification.FLAG_AUTO_CANCEL;
		        
		        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		        nm.notify(0, notification);
	        }
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void handleChatMessage(JSONObject msgData, Context context){
		try {
			String message = msgData.getString("message");
			long when = msgData.getLong("when");
			String roomId = msgData.getString("roomId");
			String speaker = msgData.getString("speaker");
			
//	        Toast.makeText(context, speaker + " : " + message, Toast.LENGTH_SHORT).show();
	        
	        if(Preferences.getBoolean(context, "configNewChat")){
		        LocalBroadcastManager localBroadMgr = LocalBroadcastManager.getInstance(context);
		        Intent intentForChatRoom = new Intent();
		        intentForChatRoom.putExtra("roomId", roomId);
		        intentForChatRoom.putExtra("message", message);
		        intentForChatRoom.putExtra("when", when);
		        intentForChatRoom.putExtra("speaker", speaker);
		        intentForChatRoom.setAction(roomId);
		        intentForChatRoom.addCategory("chatRoom");
		        
		        boolean broadResult = localBroadMgr.sendBroadcast(intentForChatRoom);
		        if(!broadResult){
		        	Notification notification = new Notification(chaw.android.train.R.drawable.ic_launcher_full, message, when);
			        Intent chatIntent = new Intent(context, ChatRoomActivity.class);
			        chatIntent.putExtra("isChat", true);
			        chatIntent.putExtra("roomId", roomId);
			        PendingIntent pi = PendingIntent.getActivity(context, 0, chatIntent, PendingIntent.FLAG_ONE_SHOT);
			        notification.setLatestEventInfo(context, "Train Travel", speaker + " : " + message, pi);
			        notification.defaults = Notification.DEFAULT_ALL;
			        notification.flags |= Notification.FLAG_AUTO_CANCEL;
			        
			        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
			        nm.notify(0, notification);
		        }
	        }
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
